#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include "Thread.hpp"

using namespace ThreadModule;

int sockfd = -1;
std::string server_ip = "0.0.0.1";
int server_port = 0;
pthread_t id;

void Send(){
	// 定义目标服务器的地址结构体
	struct sockaddr_in server;
	memset(&server, 0, sizeof(server));
	// 指定协议族为IPv4
	server.sin_family = AF_INET; 
	// 将主机字节序的服务器端口转为网络字节序
	server.sin_port = htons(server_port); 
	// 将字符串格式的服务器 IP（点分十进制）转为网络字节序的 32 位整数
	server.sin_addr.s_addr = inet_addr(server_ip.c_str());

	while(true){
		// 输入发送的消息
		std::string input;
		// std::cout<<"Please input# ";
		std::getline(std::cin, input);
		int n = sendto(sockfd, input.c_str(), input.size(), 0, (struct sockaddr*)&server, sizeof(server));
		(void)n;

		if(input == "QUIT"){
			pthread_cancel(id);
			break;
		}
	}

}

void Recv(){
	const std::string prompt = "Please input# ";
	while(true){
		// 接收服务器回复
		char buffer[1024];
		buffer[1023] = '\0';
		struct sockaddr_in peer;
		socklen_t len = sizeof(peer);
		int m = recvfrom(sockfd, buffer, sizeof(buffer)-1, 0, (struct sockaddr*)&peer, &len);
		if(m > 0){
			buffer[m] = 0;
			std::cout<<"server# "<<buffer<<std::endl;
			std::cout << prompt << std::flush;
		}	
	}
}

int main(int argc, char* argv[]){
	if(argc != 3){
		std::cerr<<"Usage: ./udpclient ip port"<<std::endl;
		return 1;
	}

	sockfd = socket(AF_INET, SOCK_DGRAM, 0);
	if(sockfd < 0){
		std::cerr<<"socket error"<<std::endl;
		return 2;
	}

	server_ip = argv[1];
	server_port = std::stoi(argv[2]);

	std::cout << "Welcome to the chat! Type 'QUIT' to exit." << std::endl;
    std::cout << "Please input# " << std::flush;

	Thread receiver(Recv);
	Thread sender(Send);

	receiver.Start();
	sender.Start();

	id = receiver.Id();

	sender.Join();
	receiver.Join();
	

	return 0;
}